﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetworkAssetManager.Entity;
using System.Management;
using log4net;

namespace NetworkAssetManager.WMI
{
    class EnvironmentVar
    {
        private static readonly ILog _logger = LogManager.GetLogger(typeof(EnvironmentVar));

        private static EntEnvironmentVars FillDetails(ManagementBaseObject obj)
        {
            EntEnvironmentVars objEnvVars = new EntEnvironmentVars();

            try
            {
                objEnvVars.Name = WMIUtil.ToString(obj["Name"]);
            }
            catch (Exception)
            {
                objEnvVars.Name = "";
            }

            try
            {
                objEnvVars.Status = WMIUtil.ToString(obj["Status"]);
            }
            catch (Exception)
            {
                objEnvVars.Status = "Unknown";
            }

            try
            {
                objEnvVars.SystemVariable = (bool)obj["SystemVariable"]; 
            }
            catch (Exception)
            {
                objEnvVars.SystemVariable = true;
            }

            try
            {
                objEnvVars.UserName = WMIUtil.ToString(obj["UserName"]);
            }
            catch (Exception)
            {
                objEnvVars.UserName= "";
            }

            try
            {
                objEnvVars.VariableValue = WMIUtil.ToString(obj["VariableValue"]);
            }
            catch (Exception)
            {
                objEnvVars.VariableValue = "";
            }

            return objEnvVars;
        }
        public static List<EntEnvironmentVars>GetEnvironmentVarDetails(ManagementScope scope)
        {
            _logger.Info("Collecting Environment variable for machine " + scope.Path.Server);

            ObjectQuery query = null;
            ManagementObjectSearcher searcher = null;
            ManagementObjectCollection objects = null;
            List<EntEnvironmentVars> lstEnvVars = new List<EntEnvironmentVars>();

            try
            {
                query = new ObjectQuery("Select * from Win32_Environment");
                searcher = new ManagementObjectSearcher(scope, query);
                objects = searcher.Get();
                lstEnvVars.Capacity = objects.Count;
                foreach (ManagementBaseObject obj in objects)
                {
                    lstEnvVars.Add(FillDetails(obj));
                    obj.Dispose();
                }
            }
            catch (System.Exception e)
            {
                _logger.Error("Exception is Environment var collection " + e.Message); 
            }
            finally
            {
                searcher.Dispose();
            }
            return lstEnvVars;
        }

    }
}
